package com.foodlocker.machine;

import java.util.HashMap;
import java.util.Map;

import com.foodlocker.bean.Machine;
import com.foodlocker.common.CommonFunction;
import com.foodlocker.common.Constant;
import com.foodlocker.common.TransPasswordUtil;
import com.foodlocker.common.UniversalHttpPost;
import com.foodlocker.common.UniversalKeyboard;


import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowId.FocusObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MachineLoginAct extends Activity {

	Button login;
	EditText machineID,secret;
	TextView  result;
	ProgressBar prgs;
	View.OnClickListener myOnClickListener;
	LinearLayout lt_mother;
	UniversalKeyboard keyboard;
	View.OnFocusChangeListener focusListener;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_machinelogin);
		init_listener();
		login=(Button) findViewById(R.id.btn_login_machinelogin);
		result=(TextView) findViewById(R.id.tv_result__act_machinelogin);
		machineID= (EditText) findViewById(R.id.et_id_act_machinelogin);
		secret= (EditText) findViewById(R.id.et_secret_act_machinelogin);
		prgs= (ProgressBar) findViewById(R.id.prgs_act_machinelogin);	
		login.setOnClickListener(myOnClickListener);
		lt_mother= (LinearLayout) findViewById(R.id.lt_mother_actmachinelogin);
		keyboard= new UniversalKeyboard(this,this,R.id.keyboard_machinelogin);
		keyboard.showKeyboard();
		keyboard.setEditText(machineID);
		prgs.setVisibility(View.GONE);					
		result.setVisibility(View.GONE);	
		machineID.setOnFocusChangeListener(focusListener);
		secret.setOnFocusChangeListener(focusListener);
		
		app_config();
	}
    
	 
	private void init_listener(){
		
		focusListener= new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus==true){
					if(v==machineID){
						keyboard.setEditText(machineID);
					}
					if(v==secret){
						keyboard.setEditText(secret);
					}
				}
				
			}
		};
		myOnClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(v==login){
					
					boolean checkinput=true;
					if(machineID.getText().toString().isEmpty()||secret.getText().toString().isEmpty()){
						checkinput=false;
						Toast.makeText(MachineLoginAct.this, "编号，密码都不能为空",Toast.LENGTH_SHORT ).show();}
			
					if(checkinput){
					    prgs.setVisibility(View.VISIBLE);					
						result.setVisibility(View.VISIBLE);		
						 result.setText("登陆中，请稍后");
						 login.setClickable(false);
				         lt_mother.setFocusable(false);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.MachineUrl;
		                params[1]="login"; //PostCod
		             								 
		                JSONObject machineJO= new JSONObject();
		                machineJO.put(Machine.ID, machineID.getText().toString());	
			          
			               try {
							String cipher= TransPasswordUtil.encrypt(secret.getText().toString()); 
							machineJO.put(Machine.SECRET, cipher); } catch (Exception e) {e.printStackTrace();}
			               JSONObject jsonData=new JSONObject();	
			               jsonData.put("machine", machineJO.toString());
			                params[2]=jsonData.toString();
		             new HttpPostTaskforLogin().execute(params);
					}
					
				}
				
				
			}
		};
	}
	

  private void app_config(){
		  
		  SharedPreferences sharedPreferences = MachineLoginAct.this.getSharedPreferences("config", Context.MODE_PRIVATE);
		  Editor editor = sharedPreferences.edit();   
		  boolean base_empty=false,owner_empty=false;
		
		  if(sharedPreferences.getString("BaseUrl", "").isEmpty()) base_empty=true;
	       if(sharedPreferences.getString("MachineUrl", "").isEmpty()) owner_empty=true;
	       if(base_empty||owner_empty){
	    	  System.out.println("-------------BaseUrl empty-----------");
	    	   editor.putString("BaseUrl", "http://192.168.1.115"); 
	    	   editor.putString("MachineUrl", ":8080/houdoudou/machine4App");
	       }
	       editor.commit(); 
	       //可能上次提交未更新 重定义。
	       SharedPreferences sP2 = MachineLoginAct.this.getSharedPreferences("config", Context.MODE_PRIVATE);
	       Constant.BaseUrl=sP2.getString("BaseUrl", "");
	       Constant.MachineUrl=sP2.getString("MachineUrl", "");  
	       String machineStr=sP2.getString("machine", "");
	       if(!machineStr.isEmpty()){ 
	    	   Constant.machineJO=JSONObject.fromObject(machineStr); 
	    	   String[] params= new String[3];
	            params[0]=Constant.BaseUrl+Constant.MachineUrl;
	            params[1]="login"; //PostCod
        	 JSONObject machineJO= new JSONObject();	    		  		        
        	    machineJO.put(Machine.ID, Constant.machineJO.getString(Machine.ID));	
        	    machineJO.put(Machine.SECRET,Constant.machineJO.getString(Machine.SECRET));
	            JSONObject jsonData=new JSONObject();	
	            jsonData.put("machine", machineJO.toString());
	        	params[2]=jsonData.toString();
	            new HttpPostTaskforLogin().execute(params);   
	            
	            prgs.setVisibility(View.VISIBLE);
	            result.setText("自动登陆中，请稍后");
	            lt_mother.setFocusable(false);            
	            machineID.setText(""+Constant.machineJO.getString(Machine.ID));
	            secret.setText("有秘密");
	       }
	 
	            
           
	  }
  private  class HttpPostTaskforLogin extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
				
			 System.out.println("-----------onPostExecute()--------------");
			 prgs.setVisibility(View.GONE);				
			 result.setVisibility(View.GONE);						
				 login.setClickable(true);
				 lt_mother.setFocusable(true);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(MachineLoginAct.this, "失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(MachineLoginAct.this, "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			    JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					 CommonFunction.alert(MachineLoginAct.this, "失败", "数据解析错误");return;
				}
				
				if(resultCode==1){ 
					CommonFunction.alert(MachineLoginAct.this, "失败", resultInfo);return;
			    	     }
				 if(resultCode==2){ //成功
					//  Toast.makeText(MachineLoginAct.this, "成功", Toast.LENGTH_SHORT).show();  
			    	  try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
					//  CommonFunction.alert(MachineLoginAct.this, "成功", "取消订单成功");  
					 
					 Constant.machineJO=jo.getJSONObject("machine");
			    	  
			    	   SharedPreferences sharedPreferences = MachineLoginAct.this.getSharedPreferences("config", Context.MODE_PRIVATE);
			 		   Editor editor = sharedPreferences.edit();   
			 		   editor.putString("machine",Constant.machineJO.toString());
			 		 //  editor.putString("Customer_Telnum",Constant.Customer_Telnum ); 
			    	  //  editor.putString("Customer_Secret", Constant.Customer_Secret);
			    	   editor.commit();		  
			    	   Intent intent= new Intent(MachineLoginAct.this, MainActivity.class);
			    	   intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    	   startActivity(intent);	    	   
					   MachineLoginAct.this.finish(); 	 
					  
					
				 }
				
			
		} //onPostExecute
	} //AsyncTask
	  
}
